#!/usr/bin/env python

import sys
import os
import string
import gobject
import time
from lib.xplanetinterface import *
from lib.impl_combogtk import *
from lib.configuration import *
from lib.systray import *
from lib.contrlWidgets import *


try:
	import pygtk
	pygtk.require("2.0")
except:
	pass

try:
	import gtk
	import gtk.glade
except:
	print "Libraries Gtk or Gtk Glade for Python not found. Please install."
	sys.exit(1)

MIN=60000

class GxPlanet:

	def exitApp(self):
		sys.exit(0)

	'''Return the Status (if is visible or not) of the Main Window'''
	def statusGUI(self):
		return self.widgets['Main'].get_property('visible')

	'''Hideing the Main Window'''
	def hideGUI(self):
		self.widgets['Main'].hide()

	'''Showing the Main Window'''
	def showGUI(self):
		self.widgets['Main'].present()

	'''When the user close the Window using the X'''
	def on_close(self,event,aux):
		self.widgets['Main'].hide()
		return True

	'''When is clicked the Refresh Button or Scheduled Refresh'''
	def refreshImage(self):
		self.xplanet.update()
		if self.dic['startup'] == "True":
			self.widgets['statusbar'].pop(1)
			self.widgets['statusbar'].push(1,"Next Refresh at %s"%(time.strftime("%H:%M:%S",time.localtime(time.time()+(self._refresh*60)))))
		else:
			self.widgets['statusbar'].pop(1)
			self.widgets['statusbar'].push(1,"Manual Actualitzation")

	def generateImage(self,dic):
		self.xplanet.execute(self.file,dic['resolution'],dic['longitude'],dic['latitude'],dic['projection'],dic['projection_parameters'])
		self.xplanet.refreshbackground()
		if dic['startup'] == "True":
			self.widgets['statusbar'].pop(1)
			self.widgets['statusbar'].push(1,"Next Refresh at %s"%(time.strftime("%H:%M:%S",time.localtime(time.time()+(self._refresh*60)))))
		else:
			self.widgets['statusbar'].pop(1)
			self.widgets['statusbar'].push(1,"Manual Actualitzation")
			

	'''Load the last Config'''	

	def loadConfiguration(self):
		if self.configuration.existoldconfig:
			dic = self.configuration.readconfig('BASIC')
			if dic:
				grade, min = string.split(dic['longitude'],'.')
				self.widgets['ULongitudeGrade'].set_text(grade)
				self.widgets['ULongitudeMinute'].set_text(min)
				grade, min = string.split(dic['latitude'],'.')
				self.widgets['ULatitudeGrade'].set_text(grade)
				self.widgets['ULatitudeMinute'].set_text(min)
				index = get_index_element(self.widgets['UResolution'],dic['resolution'])
				if index >= 0:
					self.widgets['UResolution'].set_active(index)

				index = get_index_element(self.widgets['UProjection'],dic['projection'])
				if index >= 0:
					self.widgets['UProjection'].set_active(index)

				self.widgets['UProjectionParameters'].set_text(dic['projection_parameters'])

				self.generateImage(dic)	
				if dic['startup'] == "True":
					self.widgets['UStart'].set_active(True)
					self.RefreshOptions(self.widgets['UStart'])
					self.widgets['URefresh'].set_text(dic['refresh'])
					self.startScheduler()
					self.widgets['statusbar'].push(1,"Next Refresh at %s"%(time.strftime("%H:%M:%S",time.localtime(time.time()+(self._refresh*60)))))
			else:
				dic = {
					'startup': False,
					'refresh': self._refresh,
					'longitude': '0.0',
					'latitude': '0.0',
					'resolution': self.widgets['UResolution'].get_active_text(),
					'projection': self.widgets['UProjection'].get_active_text(),
					'projection_parameters': ''
				}

			return dic


	'''Saving the Current configuration'''

	def saveConfiguration(self):
		longitude = self.widgets['ULongitudeGrade'].get_text()+"."+self.widgets['ULongitudeMinute'].get_text()
		latitude = self.widgets['ULatitudeGrade'].get_text()+"."+self.widgets['ULatitudeMinute'].get_text()
		self.dic = {
			'startup': self._slaveup,
			'refresh': self._refresh,
			'longitude': longitude,
			'latitude': latitude,
			'resolution': self.widgets['UResolution'].get_active_text(),
			'projection': self.widgets['UProjection'].get_active_text(),
			'projection_parameters': self.widgets['UProjectionParameters'].get_text()
		}
		self.configuration.saveConfiguration('BASIC',self.dic)
	
	'''Start the auto refresh & registry for Gnome startup'''

	def startScheduler(self):
		refreshold = self._refresh
		self._refresh=  self.widgets['URefresh'].get_value_as_int()
		self.configuration.startupAdded()

		if self._slaveup != True:
			self._slaveid = gobject.timeout_add(self._refresh*MIN,self.refreshImage)
			self._slaveup = True
		else:
			if refreshold != self._refresh:
				gobject.source_remove(self._slaveid)
				self._slaveid=gobject.timeout_add(self._refresh*MIN,self.refreshImage)


	'''Remove the Startup & auto refresh'''	

	def stopScheduler(self):
		self._refresh = 0
		self.configuration.startupRemoved()
		if self._slaveup:
			gobject.source_remove(self._slaveid)
			self._slaveup = False

	'''Function when the user press Close or Close window'''
	def OkcloseWindow(self,widget):
		if self.widgets['UStart'].get_active():
			self.dic['startup']="True"
			self.startScheduler()
		else:
			self.dic['startup']="False"
			self.stopScheduler()

		self.generateImage(self.dic)
		self.saveConfiguration()	
		self.widgets['Main'].hide()

	'''Function when the user press Reset Values'''
	def ResetValues(self,widget):
		grade, min = string.split(self.dic['longitude'],'.')
		self.widgets['ULongitudeGrade'].set_text(grade)
		self.widgets['ULongitudeMinute'].set_text(min)
		grade, min = string.split(self.dic['latitude'],'.')
		self.widgets['ULatitudeGrade'].set_text(grade)
		self.widgets['ULatitudeMinute'].set_text(min)
		index = get_index_element(self.widgets['UResolution'],self.dic['resolution'])
		if index >= 0:
			self.widgets['UResolution'].set_active(index)

		index = get_index_element(self.widgets['UProjection'],self.dic['projection'])
		if index >= 0:
			self.widgets['UProjection'].set_active(index)

		self.widgets['UProjectionParameters'].set_text(self.dic['projection_parameters'])
		if self.dic['startup'] == "True":
			self.widgets['UStart'].set_active(True)
			self.RefreshOptions(self.widgets['UStart'])
			self.widgets['URefresh'].set_text(self.dic['refresh'])


	'''Function for do the interactive graphic components'''
	def projectionChange(self,widget):
		val= get_active_text(widget)
		if val == "Bonne" or val == "Gnomonic" or val == "Mercator" :
			self.widgets['UProjectionParameters'].show()
			self.widgets['lParameters'].show()
		else:
			self.widgets['UProjectionParameters'].set_text('')
			self.widgets['UProjectionParameters'].hide()
			self.widgets['lParameters'].hide()


	'''When the Gxplanet start with Gnome'''
	def RefreshOptions(self,widget):
	    if widget.get_active():
	        self.widgets['lRefresh'].show()
	        self.widgets['URefresh'].show()
	        self.widgets['lRefreshMins'].show()
	    else:
	        self.widgets['lRefresh'].hide()
	        self.widgets['lRefreshMins'].hide()
	        self.widgets['URefresh'].hide()
	        
	
	def __init__(self):
		self._refresh=0
		self._slaveup = False
		self.id_thread = 0
		self.user = os.environ['USER']
		self.configuration = Configuration(os.environ['HOME']+"/")
		self.file = "/tmp/"+self.user+"-xplanet-wallpaper.png"
		self.xplanet = XplanetI()
		self.widgets = Widgets('/opt/Gxplanet/gui/gxplanet.glade')
		self.widgets['Main'].hide()
		connections = {
			'on_bReset_clicked': self.ResetValues,
			'on_bOk_clicked': self.OkcloseWindow,
			'on_UProjection_changed': self.projectionChange,
			'on_UStart_toggled': self.RefreshOptions
			}
		self.widgets.autoconnect(connections)
		self.widgets['UResolution'].set_active(2)
		self.widgets['UProjection'].set_active(0)
		self.widgets['Main'].connect("delete-event",self.on_close)
		self.dic=self.loadConfiguration()

if __name__ == "__main__":
	gxplanet = GxPlanet()
	systray = GxplanetStatusIcon(gxplanet)
	gtk.main()
	
